﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace MinIODemo.Web.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class HomeController : ControllerBase
    {
        private readonly MinioClient _minioClient;

        public HomeController(MinioClient minioClient)
        {
            _minioClient = minioClient;
        }

        [HttpPost("/CreateBucket")]
        public async Task CreateBucketAsync(string bucketName)
        {
            var existedBucket = await _minioClient.BucketExistsAsync(bucketName);
            if (!existedBucket)
            {
                await _minioClient.MakeBucketAsync(bucketName);
            }
        }

        /// <summary>
        /// https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/userguide/access-policy-language-overview.html
        /// https://awspolicygen.s3.amazonaws.com/policygen.html
        /// </summary>
        /// <param name="bucketName"></param>
        /// <param name="policyJson"></param>
        /// <returns></returns>
        [HttpPost("/UpdatePolicy")]
        public async Task UpdatePolicyAsync(string bucketName, string prefix)
        {
            var existedBucket = await _minioClient.BucketExistsAsync(bucketName);
            if (existedBucket)
            {
                //var defaultPolicy = await _minioClient.GetPolicyAsync(bucketName);
                //固定格式只需变更prefix即可
                var policyJson = $@"{{""Version"":""2012-10-17"",""Statement"":[{{""Action"":[""s3:GetBucketLocation""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:ListBucket""],""Condition"":{{""StringEquals"":{{""s3:prefix"":[""{prefix}""]}}}},""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}""],""Sid"":""""}},{{""Action"":[""s3:GetObject""],""Effect"":""Allow"",""Principal"":{{""AWS"":[""*""]}},""Resource"":[""arn:aws:s3:::{bucketName}/{prefix}*""],""Sid"":""""}}]}}";
                await _minioClient.SetPolicyAsync(bucketName, policyJson);
            }
        }

        [HttpPost("/UploadFile")]
        public async Task<int> UploadFileAsync(string bucketName, List<IFormFile> files)
        {
            var size = files.Sum(f => f.Length);
            try
            {
                foreach (var formFile in files)
                {
                    var saveFileName = $"{Guid.NewGuid():N}{Path.GetExtension(formFile.FileName)}";
                    var objectName = $"/{DateTime.Now:yyyy/MM/dd}{saveFileName}";

                    if (formFile.Length > 0)
                    {
                        var stream = formFile.OpenReadStream();
                        await _minioClient.PutObjectAsync(bucketName, objectName, stream, formFile.Length, formFile.ContentType);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

            return files.Count;
        }
    }
}
